<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>试剂到期信息</title>
    <!-- Bootstrap 5 CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="css/bootstrap-icons.css" rel="stylesheet">
    <!-- 自定义样式 -->
    <link rel="stylesheet" href="css/style.css">
    <style>
        /* 状态样式 */
        .status-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.875rem;
        }
        
        .status-warning {
            background-color: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.875rem;
        }
        
        .status-danger {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.875rem;
        }
        
        .status-info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.875rem;
        }
        
        .status-badge {
            display: inline-flex;
            align-items: center;
            white-space: nowrap;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark navbar-custom">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">实验室管理系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="page1.html">试剂列表</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="page2.html">试剂使用列表</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="page3.html">实验室预警信息看板</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="page4.html">试剂到期预警</a>
                    </li>
                </ul>
                <!-- 用户信息和退出登录 -->
                <div class="dropdown">
                    <a class="nav-link dropdown-toggle text-white" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="bi bi-person-circle me-1"></i>
                        <span id="currentUserName">加载中...</span>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                        <li><a class="dropdown-item" href="#" id="logoutBtn"><i class="bi bi-box-arrow-right me-2"></i>退出登录</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <div class="container-fluid">
        <div class="main-content">
            <!-- 页面标题 -->
            <div class="page-header">
                <h3 class="page-title mb-0">试剂到期信息</h3>
            </div>

            <!-- 数据表格 -->
            <div class="table-container">
                <table class="table table-hover data-table">
                    <thead>
                        <tr>
                            <th style="width: 80px;">序号</th>
                            <th style="width: 200px;">试剂名称</th>
                            <th style="width: 150px;">批号</th>
                            <th style="width: 150px;">到期日期</th>
                            <th style="width: 120px;">剩余天数</th>
                            <th>状态</th>
                        </tr>
                    </thead>
                    <tbody id="dataTableBody">
                        <!-- 数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>

            <!-- 空状态 -->
            <div id="emptyState" class="text-center py-5" style="display: none;">
                <div class="mb-4">
                    <i class="bi bi-inbox text-muted" style="font-size: 4rem;"></i>
                </div>
                <h4 class="text-muted">暂无试剂数据</h4>
                <p class="text-muted">请先在试剂列表中添加试剂信息</p>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="pagination-info">
                        <span id="paginationInfo">显示 0-0 条，共 0 条记录</span>
                    </div>
                    <nav aria-label="分页导航">
                        <ul class="pagination pagination-sm mb-0" id="pagination">
                            <!-- 分页按钮将通过JavaScript动态生成 -->
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap 5 JS -->
    <script src="js/bootstrap.bundle.min.js"></script>
    <!-- 自定义JavaScript -->
    <script src="js/common.js"></script>
    <script>
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 0;
        let allReagentData = [];
        let filteredData = [];

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadAllExpiryData();
            // 每5分钟自动刷新一次
            setInterval(loadAllExpiryData, 5 * 60 * 1000);
        });

        // 加载所有试剂到期数据
        async function loadAllExpiryData() {
            try {
                // 最后更新时间（已移除显示）
                
                // 获取所有试剂数据
                allReagentData = await fetchAllData('page1');
                
                // 计算所有试剂到期数据
                const allExpiryData = calculateAllExpiryData();
                
                // 显示数据
                displayAllExpiryData(allExpiryData);
                
            } catch (error) {
                showAlert('error', '加载试剂到期数据失败: ' + error.message);
            }
        }

        // 获取所有数据（分页获取）
        async function fetchAllData(page) {
            let allData = [];
            let currentPageNum = 1;
            let hasMore = true;
            
            while (hasMore) {
                const result = await Http.get('/api/data', {
                    page: page,
                    pageNum: currentPageNum,
                    pageSize: 100
                });
                
                if (result.success) {
                    allData = allData.concat(result.data);
                    hasMore = currentPageNum < result.pagination.totalPages;
                    currentPageNum++;
                } else {
                    hasMore = false;
                }
            }
            
            return allData;
        }

        // 计算所有试剂的到期数据
        function calculateAllExpiryData() {
            const allItems = [];
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            
            allReagentData.forEach(reagent => {
                let daysLeft = null;
                let status = '';
                let statusClass = '';
                let statusIcon = '';
                let isCritical = false;
                let isWarning = false;
                
                if (reagent.expiry_date) {
                    const expiryDate = new Date(reagent.expiry_date);
                    expiryDate.setHours(0, 0, 0, 0);
                    
                    const timeDiff = expiryDate - today;
                    daysLeft = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
                    
                    if (daysLeft <= 10) {
                        status = '即将过期';
                        statusClass = 'status-danger';
                        statusIcon = 'bi-exclamation-triangle';
                        isCritical = true;
                        isWarning = true;
                    } else if (daysLeft <= 30) {
                        status = '即将到期';
                        statusClass = 'status-warning';
                        statusIcon = 'bi-clock';
                        isWarning = true;
                    } else {
                        status = '正常';
                        statusClass = 'status-success';
                        statusIcon = 'bi-check-circle';
                    }
                } else {
                    status = '无到期日期';
                    statusClass = 'status-info';
                    statusIcon = 'bi-info-circle';
                }
                
                allItems.push({
                    id: reagent.id,
                    name: reagent.material_name,
                    batch: reagent.batch_number,
                    expiryDate: reagent.expiry_date || '-',
                    daysLeft: daysLeft,
                    status: status,
                    statusClass: statusClass,
                    statusIcon: statusIcon,
                    isCritical: isCritical,
                    isWarning: isWarning
                });
            });
            
            // 排序：预警的在前面（先紧急后一般预警），然后按剩余天数升序排序
            allItems.sort((a, b) => {
                // 紧急预警（10天内）优先
                if (a.isCritical && !b.isCritical) return -1;
                if (!a.isCritical && b.isCritical) return 1;
                
                // 一般预警（30天内）次之
                if (a.isWarning && !b.isWarning) return -1;
                if (!a.isWarning && b.isWarning) return 1;
                
                // 同级别按剩余天数排序
                if (a.daysLeft !== null && b.daysLeft !== null) {
                    return a.daysLeft - b.daysLeft;
                }
                
                // 有到期日期的优先于无到期日期的
                if (a.daysLeft !== null && b.daysLeft === null) return -1;
                if (a.daysLeft === null && b.daysLeft !== null) return 1;
                
                return 0;
            });
            
            return allItems;
        }

        // 更新统计信息（已简化，不再显示统计卡片）
        function updateStatistics(expiryData) {
            // 统计功能已移除
        }



        // 显示所有试剂到期数据
        function displayAllExpiryData(allData) {
            const tbody = document.getElementById('dataTableBody');
            const emptyState = document.getElementById('emptyState');
            const tableContainer = document.querySelector('.table-container');
            const paginationContainer = document.querySelector('.pagination-container');
            
            if (allData.length === 0) {
                // 显示空状态
                tableContainer.style.display = 'none';
                paginationContainer.style.display = 'none';
                emptyState.style.display = 'block';
                return;
            }
            
            // 显示表格
            tableContainer.style.display = 'block';
            paginationContainer.style.display = 'block';
            emptyState.style.display = 'none';
            
            // 分页处理
            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = startIndex + pageSize;
            const pageData = allData.slice(startIndex, endIndex);
            
            tbody.innerHTML = '';
            
            pageData.forEach((item, index) => {
                // 根据状态确定剩余天数显示的颜色
                let daysBadgeClass = 'bg-light text-dark';
                if (item.daysLeft !== null) {
                    if (item.isCritical) {
                        daysBadgeClass = 'bg-danger text-white';
                    } else if (item.isWarning) {
                        daysBadgeClass = 'bg-warning text-dark';
                    } else {
                        daysBadgeClass = 'bg-success text-white';
                    }
                }
                
                const row = `
                    <tr class="fade-in">
                        <td>${startIndex + index + 1}</td>
                        <td>
                            <div class="d-flex align-items-center">
                                <i class="bi bi-flask text-primary me-2"></i>
                                <strong>${item.name}</strong>
                            </div>
                        </td>
                        <td class="text-muted">${item.batch || '-'}</td>
                        <td>
                            <span class="badge bg-light text-dark">
                                ${item.expiryDate}
                            </span>
                        </td>
                        <td>
                            <span class="badge ${daysBadgeClass}">
                                ${item.daysLeft !== null ? (item.daysLeft >= 0 ? item.daysLeft : 0) + ' 天' : '-'}
                            </span>
                        </td>
                        <td>
                            <span class="status-badge ${item.statusClass}">
                                <i class="bi ${item.statusIcon} me-1"></i>
                                ${item.status}
                            </span>
                        </td>
                    </tr>
                `;
                tbody.innerHTML += row;
            });
            
            // 更新分页
            updatePagination({
                total: allData.length,
                totalPages: Math.ceil(allData.length / pageSize),
                currentPage: currentPage,
                pageSize: pageSize
            });
        }

        // 更新分页
        function updatePagination(pagination) {
            totalPages = pagination.totalPages;
            const paginationElement = document.getElementById('pagination');
            const paginationInfo = document.getElementById('paginationInfo');
            
            // 更新信息
            const startRecord = (currentPage - 1) * pageSize + 1;
            const endRecord = Math.min(currentPage * pageSize, pagination.total);
            paginationInfo.textContent = `显示 ${startRecord}-${endRecord} 条，共 ${pagination.total} 条记录`;
            
            // 生成分页按钮
            let paginationHTML = '';
            
            if (totalPages <= 1) {
                paginationElement.innerHTML = '';
                return;
            }
            
            // 上一页
            if (currentPage > 1) {
                paginationHTML += `<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="changePage(${currentPage - 1})"><i class="bi bi-chevron-left"></i></a></li>`;
            } else {
                paginationHTML += `<li class="page-item disabled"><span class="page-link"><i class="bi bi-chevron-left"></i></span></li>`;
            }
            
            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === currentPage) {
                    paginationHTML += `<li class="page-item active"><span class="page-link">${i}</span></li>`;
                } else {
                    paginationHTML += `<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="changePage(${i})">${i}</a></li>`;
                }
            }
            
            // 下一页
            if (currentPage < totalPages) {
                paginationHTML += `<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="changePage(${currentPage + 1})"><i class="bi bi-chevron-right"></i></a></li>`;
            } else {
                paginationHTML += `<li class="page-item disabled"><span class="page-link"><i class="bi bi-chevron-right"></i></span></li>`;
            }
            
            paginationElement.innerHTML = paginationHTML;
        }

        // 切换页面
        function changePage(page) {
            currentPage = page;
            // 重新计算并显示当前页的到期数据
            const allExpiryData = calculateAllExpiryData();
            displayAllExpiryData(allExpiryData);
        }

        // 显示提示信息
        function showAlert(type, message) {
            // 创建 toast 提示
            const toastContainer = document.getElementById('toastContainer') || createToastContainer();
            const toast = document.createElement('div');
            toast.className = `toast align-items-center text-white bg-${type === 'error' ? 'danger' : type === 'warning' ? 'warning' : 'success'} border-0`;
            toast.setAttribute('role', 'alert');
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">
                        <i class="bi bi-${type === 'error' ? 'exclamation-triangle' : type === 'warning' ? 'exclamation-circle' : 'check-circle'} me-2"></i>
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            `;
            
            toastContainer.appendChild(toast);
            const bsToast = new bootstrap.Toast(toast);
            bsToast.show();
            
            // 自动移除
            toast.addEventListener('hidden.bs.toast', () => {
                toast.remove();
            });
        }

        // 创建 toast 容器
        function createToastContainer() {
            const container = document.createElement('div');
            container.id = 'toastContainer';
            container.className = 'toast-container position-fixed top-0 end-0 p-3';
            container.style.zIndex = '9999';
            document.body.appendChild(container);
            return container;
        }
        
        // 初始化用户信息
        function initUserInfo() {
            const currentUser = Auth.getCurrentUser();
            if (currentUser) {
                document.getElementById('currentUserName').textContent = currentUser;
            }
        }
        
        // 添加退出登录事件
        document.getElementById('logoutBtn').addEventListener('click', function(e) {
            e.preventDefault();
            Auth.logout();
        });
        
        // 页面加载完成后初始化用户信息
        document.addEventListener('DOMContentLoaded', function() {
            initUserInfo();
        });
    </script>
</body>
</html>